import React,{useEffect, useRef, useState} from "react";
import {Tabs,Form,Select,Input,Tooltip,Button,Image,Tag,Popover,notification,Modal,message} from 'antd'
import LlxForm from 'components/LlxForm/index'
import classNames from "classnames";
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries,checkPublishData} from 'redux/action'
import LlxTable from 'components/LlxTable'
import {getExploreData, queryPageOfExtensiveArea,bulkeditingexplore, queryPageOfTeachingArea,pushExploreData, delExploreData, getExploreDataBook, getExploreVideoData, queryExplorePoolByLeVideo} from 'api/index'
import PushNewBook from 'components/LlxPushData/newBook'
import PushVideo from 'components/LlxPushData/video'
import PushStudy from 'components/LlxPushData/studyVideo'
import PushBook from 'components/LlxPushData/book'
import PreviewVideo from 'components/LlxPreview/video'
import PreviewBook from 'components/LlxPreview/book'
import PreviewWordSubject from "components/LlxPreview/afterPreview";

const {TabPane} = Tabs
const {Search} = Input
const list = [
    {pid:'410',name:'教学区',value:'全部',id:1},
    {pid:'410',name:'教学区',value:'精读书',id:411},
    {pid:'410',name:'教学区',value:'学习视频',id:412},
    {pid:'510',name:'泛读区',value:'全部',id:2},
    {pid:'510',name:'泛读区',value:'泛读书',id:511},
    {pid:'510',name:'泛读区',value:'视频',id:512}
]


const ClassifyData = (props) => {
  const {isModalVisible, setIsModalVisible,dataId,form,options,types} = props

  const loading = useRef(false)

  const [formItems] = Form.useForm()
  
  // 新增表单
const newWordItem = [
  {label: '等级',name: 'gradeId' , span: 20, rules:[
    {
      required: true,
      message: '请选择等级'
    },
  ],render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择等级'}
    options= {options}
  >
  </Select>
  } }
]

  const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    formItems.validateFields().then(async()=>{

       if(types.id){
         await bulkeditingexplore(types.id.map(i=>{
           return {id:i,gradeId:formItems.getFieldValue().gradeId}
         }))

         notification.success({
          message: '修改成功',
          duration:1
        });

         setIsModalVisible(false);

         props.getNewList()

        return
       }
      const data = {
        dataId: dataId,
        districtId:  types.districtId,
        gradeId: formItems.getFieldValue().gradeId,
        levelId: form.getFieldValue().levelId||106,
        modelId: types.modelId,
        type: types.type
      }


      await pushExploreData(data)
    
      notification.success({
        message: '添加成功',
        duration:1
      });


      formItems.resetFields()
      setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
      console.log(err);
    }).finally(()=>{
      loading.current=false
    })
  };

  const handleCancel = () => {
    formItems.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal destroyOnClose width={700} title="选择电影院分类" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={formItems} labelCol={8} formItem={newWordItem} />
   </Modal>
}





function VideoPool(props) {

const {dictionaries} = props
const userName = props.userInfo.userName
const [form] = Form.useForm()
const [loading,setLoading] = useState(false)
const [total,setTotal] = useState(false)
const [tabIndex,setTabIndex] = useState('1')
const [dataId,setDataId] = useState([]) // 新增的id
const [items,setItems] = useState({})
const [previewBook,setPreviewBook] = useState(false)
const [previewVideo,setPreviewVideo] = useState(false)
const [previewStudy,setPreviewStudy] = useState(false)
const [isModalVisibleClassify,setIsModalVisibleClassify] = useState(false)
const [isModalVisiblePushBook,setIsModalVisiblePushBook] = useState(false)
const [isModalVisiblePushVideo,setIsModalVisiblePushVideo] = useState(false)
const [isModalVisiblePushStudy,setIsModalVisiblePushStudy] = useState(false)
const [isModalVisiblePushNewBook,setIsModalVisiblePushNewBook] = useState(false)
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
const columns = [
  {title: '名称',fixed:'left', dataIndex: 'name',width:250, key: 'name', align: 'center',render: (text, record) => {
    return <div className="operate_link_group text-nowrap text-link" onClick={()=>goInfo(record)}>
      {text}
   </div>
 }},
 {title: '级别', dataIndex: 'levelName',width:100, key: 'levelName', align: 'center'},
 {title: '探索级别', dataIndex: 'gradeName',width:100, key: 'gradeName', align: 'center'},
 {title: '类型', dataIndex: 'modelName',width:100, key: 'modelName', align: 'center'},
 {title: '素材状态', dataIndex: 'upperLowerName',width:100, key: 'upperLowerName', align: 'center',render: (text, record) => {
  return <div className="operate_link_group text-nowrap">
    {
      text==='已上架'?<Tag  color="success">{text}</Tag>:<Tag  color="red">{text}</Tag>
    }
 </div>}},
  {title: '封面', dataIndex: 'pictureUrl',width:150, key: 'pictureUrl', align: 'center',render:(text)=>{
    return  <div>
      {
        text?<Image
        width={60}
        src={text}
      />:''
      }
    </div>
  }},
  {title: '适合年纪', dataIndex: 'ageName',width:100, key: 'ageName', align: 'center'},
  {title: '发行方', dataIndex: 'publisher',width:150, key: 'publisher', align: 'center'},
  {title: '主题', dataIndex: 'themes',width:180, key: 'themes', align: 'center', render: (text, record) => {
    return <div className="operate_link_group text-nowrap">
     {record.themes?.map((i,j)=>{
       return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.themeName).join(' ')}>
        {
          j<3?<Tag key={i.id} color="lime">{i.themeName}</Tag>:''
        }
         </Tooltip>
     })}
   </div>}
  },
  {title: '系列', dataIndex: 'serialName',width:150, key: 'serialName', align: 'center'},
  {title: '标签', dataIndex: 'labels', key: 'labels',width:180, align: 'center', render: (text, record) => {
   return <div className="operate_link_group text-nowrap">
    {record.labels?.map((i,j)=>{
      return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.labelName).join(' ')}>
       {
         j<3?<Tag key={i.id} color="green">{i.labelName}</Tag>:''
       }
        </Tooltip>
    })}
  </div>
}},
  {title: '创建人',width:120, dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
    return <div className={classNames(userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
      {text}
   </div>
 }},
  {title: '更新人',width:120, dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
    return  <div className={classNames(userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
    {text}
 </div>
 }},
  {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:180},
  {title: '操作',fixed:'right', dataIndex: 'operate', key: 'operate', align: 'center',width:100,render:(text,row)=>{
    return  <div className="text-link" onClick={()=>previewData(row)}>
     预览
   </div>
  }}
]

// 表单数据
const formItem = [
  {label: '级别', name: 'levelId', span: 4,render: () => {
    return <Select
    allowClear
    defaultValue={106}
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
}},
{label: '等级', name: 'gradeId', span: 4,render: () => {
  return <Select
  allowClear
  optionFilterProp="dictValue"
  showSearch
  fieldNames={{value:'id',label:'dictValue'}}
  placeholder={'请选择等级'}
  options={dictionaries.LevelExplore}
>
</Select>
}},
{label: '素材状态', name: 'upperLower', span: 4,render: () => {
  return <Select
  allowClear
  optionFilterProp="dictValue"
  showSearch
  fieldNames={{value:'id',label:'dictValue'}}
  placeholder={'请选择状态'}
  options={[{dictValue:'已上架',id:1010},{dictValue:'已下架',id:1000}]}
>
</Select>
}},
{label: '创建人', name: 'createBy',  span: 4 ,render: () => {
  return <Select
  allowClear
  optionFilterProp="userName"
  showSearch
  fieldNames={{value:'userName',label:'userName'}}
  placeholder={'请选择创建人'}
  options={dictionaries.UserSpecies}
>
</Select>
}},
{label: '', name: 'name' , span: 4,render: () => {
    return  <Search placeholder="请输入关键词搜索" onSearch={getNewList} enterButton />
} }
]
//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})

// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='areaPush/explorePool')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='areaPush/explorePool')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps

// 1.切换tab
const callback = (key)  => {
    setTabIndex(key)
    setPagination({
      current:1,
      pageSize:20
    })
}
// 1.1
  useEffect(()=>{
    getNewList()
  },[tabIndex]) // eslint-disable-line react-hooks/exhaustive-deps

  // 2.获取数据
  const getNewList = async(value) => {
      setIsModalVisiblePushBook(false)
      setIsModalVisiblePushNewBook(false)
      setIsModalVisiblePushVideo(false)
      setIsModalVisiblePushStudy(false)
    // 清空选中状态
   setselectedRowKeys(()=>[])
   rowSelection.current.selectedRowKeys=[]

   setLoading(true)

    
  //  请求数据
   const params = {
    currPage:value&&value.pageSize?value.current:pagination.current,
    pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize,
    createBy:form.getFieldValue().createBy,
    levelId:form.getFieldValue().levelId || 106,
    name:form.getFieldValue().name,
    upperLower:form.getFieldValue().upperLower,
    districtId: list.filter(i=>i.id===+tabIndex)[0].pid,
    modelId: +tabIndex>100?tabIndex:'',
    gradeId: form.getFieldValue().gradeId
  }

  if(props.tabList.filter(i=>i.url==='areaPush/explorePool')[0]?.data?.pagination&&(props.tabList.filter(i=>i.url==='areaPush/explorePool')[0]?.data?.pagination.current!==1||props.tabList.filter(i=>i.url==='areaPush/explorePool')[0]?.data?.pagination.pageSize!==10)&&pagination.current===1&&pagination.pageSize===10){
    params.currPage=props.tabList.filter(i=>i.url==='areaPush/explorePool')[0]?.data?.pagination.current
    params.pageSize=props.tabList.filter(i=>i.url==='areaPush/explorePool')[0]?.data?.pagination.pageSize
  }

  const data = {
    pagination: value&&value.pageSize?value:pagination,
    form:form.getFieldValue()
 }
   props.setPageDataFn('areaPush/explorePool',data) 


  if (+tabIndex===1) {
    const res = await queryPageOfTeachingArea(params)
    const data1= res.result.records
    data1.forEach((i,j)=>{
      i.sort=j+1
    })
    setDataSource(()=>data1)
    setTotal(res.result.total)
  }
  if (+tabIndex===2) {
    const res = await queryPageOfExtensiveArea(params)
    const data1= res.result.records
    data1.forEach((i,j)=>{
      i.sort=j+1
    })
    setDataSource(()=>data1)
    setTotal(res.result.total)
  }
  if (+tabIndex === 411) {
    const res = await getExploreData(params)
    const data1= res.result.records
    data1.forEach((i,j)=>{
      i.sort=j+1
    })
    setDataSource(()=>data1)
    setTotal(res.result.total)
  } else if (+tabIndex === 512) {
    const res = await getExploreVideoData(params)
    const data1= res.result.records
    data1.forEach((i,j)=>{
      i.sort=j+1
    })
    setDataSource(()=>data1)
    setTotal(res.result.total)
  } else if (+tabIndex === 412) {
    const res = await queryExplorePoolByLeVideo(params)
    const data1= res.result.records
    data1.forEach((i,j)=>{
      i.sort=j+1
    })
    setDataSource(()=>data1)
    setTotal(res.result.total)
  } else if (+tabIndex === 511) {
    const res = await getExploreDataBook(params)
    const data1= res.result.records
    data1.forEach((i,j)=>{
      i.sort=j+1
    })
    setDataSource(()=>data1)
    setTotal(res.result.total)
  }
  setLoading(false)
  }
//  3.去详情
const goInfo = (value) => {
   props.checkPublishDataBtn(true)
  switch(value.type) {
    case '视频':
      props.history.push('/view/video/videoInfo?id=' + value.id)
      props.addRouter({
        menuName:'视频详情',url:'video/videoInfo?id=' + value.id 
      })
    break
    case '学习视频':
      props.history.push('/view/video/studyInfo?id=' + value.id)
      props.addRouter({
        menuName:'学习视频详情',url:'video/studyInfo?id=' + value.id 
      })
    break
    case '精读书':
      props.history.push('/view/book/intensiveBookInfo?id=' + value.id)
      props.addRouter({
        menuName:'精读书详情',url:'book/intensiveBookInfo?id=' + value.id 
      })
    break
    case '泛读书':
      props.history.push('/view/book/bookInfo?id=' + value.id)
      props.addRouter({
        menuName:'泛读详情',url:'book/bookInfo?id=' + value.id 
      })
    break
    default:
      return
    }
}
// 4.拉取音频数据
const pushArea = (value) => {
    switch(value) {
      case 'BOOK':
        setIsModalVisiblePushBook(true)
      break
      case 'IR_BOOK':
        setIsModalVisiblePushNewBook(true)
      break
      case 'VIDEO':
        setIsModalVisiblePushVideo(true)
      break
      case 'LE_VIDEO':
        setIsModalVisiblePushStudy(true)
      break
      default:
        return
    }
}
// 修改等级
const editLevel = () => {
  setItems({
    id:dataSource.filter((i)=>selectedRowKeys.includes(i.sort)).map(i=>i.explorePoolId)
  })
  setIsModalVisibleClassify(true)
}
// 移除探索区
const removeArea = async() => {
  await delExploreData(dataSource.filter((i)=>selectedRowKeys.includes(i.sort))
.map(i => {
    return {
      id: i.explorePoolId,
      status: 0
    }
  }))
  message.success('移除成功')
  getNewList()
}
const returnBookId = (value) => {
  setItems({
    type:'BOOK',
    modelId:511,
    districtId:510,
    id:''
  })
    setDataId(value)
  setIsModalVisibleClassify(true)
}
const returnNewBookId = (value) => {
  setItems({
    type:'IR_BOOK',
    modelId:411,
    districtId:410,
    id:''
  })
    setDataId(value)
  setIsModalVisibleClassify(true)
}
const returnVideoId = (value) => {
  setItems({
    type:'VIDEO',
    modelId:512,
    districtId:510,
    id:''
  })
    setDataId(value.map(i=>i.id))
  setIsModalVisibleClassify(true)
}
const returnStudyId = (value) => {
  setItems({
    type:'LE_VIDEO',
    modelId:412,
    districtId:410,
    id:''
  })
    setDataId(value)
  setIsModalVisibleClassify(true)
}
const previewData =(value) => {
  switch(value.modelName) {
    case '视频':
      setItems({
        videoUrl:value.videoUrl,
        srtUrl:value.videoSrt
      })
      setPreviewVideo(true)
    break
    case '学习视频':
      setItems({id:value.dataId })
      setPreviewStudy(true)
    break
    case '精读书':
      setItems({id:value.parentBookId + '?' +Math.random*100})
      setPreviewBook(true)
    break
    case '泛读书':
      setItems({id:value.parentBookId+ '?' +Math.random*100})
      setPreviewBook(true)
    break
    default:
      return
    }
}


     return  <div  className="app-content animate__animated animate__fadeIn overflow">

    <LlxForm form={form} formItem={formItem}/>

    <div className="operate-btn">
     <div>
           
           <Popover  content={
             <>
             <span onClick={()=>pushArea('IR_BOOK')} className='text-link'>精读书</span>&nbsp;&nbsp;
             <span onClick={()=>pushArea('BOOK')} className='text-link'>泛读书</span>&nbsp;&nbsp;
             <span onClick={()=>pushArea('VIDEO')} className='text-link'>视频</span>&nbsp;&nbsp;
             <span onClick={()=>pushArea('LE_VIDEO')} className='text-link'>学习视频</span>
             </>
           } title="选择新增类型">
             <Button type='primary' className='animate__animated animate__fadeInLeft'>新增</Button>
           </Popover>
           <Button disabled={!selectedRowKeys.length} onClick={editLevel} type='primary' className='animate__animated animate__fadeInLeft'>批量修改等级</Button>

           <Button danger onClick={removeArea} disabled={!selectedRowKeys.length} type='primary' className='animate__animated animate__fadeInLeft'>移除探索区</Button>
       </div>
    </div>

    <Tabs  activeKey={tabIndex} onChange={callback} className="app-content animate__animated animate__fadeIn">
      {
        list.map((i,j)=>{
          return  <TabPane tab={i.name + '+' + i.value} key={i.id}>
          <LlxTable
          loading={loading} 
          pagination={pagination}
          setPagination={setPagination}
          selectedRowShow={true}
          rowSelection={rowSelection.current}
          height={360}
          total={total}
          keyName={'sort'}
          getNewList={getNewList}
          columns={columns}
          dataSource={dataSource}/>
       </TabPane>
        })
      }
    </Tabs>


    <PushBook returnBookId={returnBookId} title={'探索新增泛读'} multipleType={true} userName={props.userInfo.user.userName} dictionaries={props.dictionaries} isModalVisible={isModalVisiblePushBook} setIsModalVisible={setIsModalVisiblePushBook}></PushBook>
    <PushNewBook returnNewBookId={returnNewBookId} title={'探索新增精读'} multipleType={true} userName={props.userInfo.user.userName} dictionaries={props.dictionaries} isModalVisible={isModalVisiblePushNewBook} setIsModalVisible={setIsModalVisiblePushNewBook}></PushNewBook>
    
    <PushVideo returnSelect={returnVideoId} title={'探索新增视频'} multipleType={true} userName={props.userInfo.user.userName} dictionaries={props.dictionaries} isModalVisible={isModalVisiblePushVideo} setIsModalVisible={setIsModalVisiblePushVideo}></PushVideo>
    <PushStudy returnStudyId={returnStudyId} title={'探索新增专辑'} multipleType={true} userName={props.userInfo.user.userName} dictionaries={props.dictionaries} isModalVisible={isModalVisiblePushStudy} setIsModalVisible={setIsModalVisiblePushStudy}></PushStudy>
    
    
    <PreviewBook id={items.id}  isModalVisible={previewBook} setIsModalVisible={setPreviewBook}></PreviewBook>
     
    
    <ClassifyData types={items} getNewList={getNewList} form={form} dataId={dataId} options={dictionaries.LevelExplore} isModalVisible={isModalVisibleClassify} setIsModalVisible={setIsModalVisibleClassify}></ClassifyData>
  
     {/* 预览视频 */}
     <PreviewVideo prevewVideo={items} isModalVisible={previewVideo} setIsModalVisible={setPreviewVideo} ></PreviewVideo>
     {/* 预览学习视频 */}
      <PreviewWordSubject type={'study'} id={items.id} isModalVisible={previewStudy} setIsModalVisible={setPreviewStudy}></PreviewWordSubject>
     </div>
}


// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    checkPublishDataBtn: () => dispatch(checkPublishData()),
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(VideoPool)
